<<<<<<< HEAD
from . import admin_bp 
from flask import request,jsonify
from app.models import ModuleType,OperationType,User
from app.models import OperationLog,Role,Permission,RolePermission
from app.extensions import db
from app.decorator import permission_required

@admin_bp.route('/admin/role/list',methods=['GET'])
=======
from . import admin_bp
from flask import request, jsonify
from app.models import ModuleType, OperationType, User
from app.models import OperationLog, Role, Permission, RolePermission
from app.extensions import db
from app.decorator import permission_required


@admin_bp.route('/admin/role/list', methods=['GET'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_ROLE, OperationType.QUERY)
def role_list():
    page = request.args.get('page', type=int)
    page_size = request.args.get('pageSize', type=int)
    search_key = request.args.get('searchKey', type=str)
    uid = request.args.get('uid', type=int)
<<<<<<< HEAD
    
    # 创建基础查询
    query = Role.query
    
=======

    # 创建基础查询
    query = Role.query

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    # 如果有搜索关键词，添加过滤条件
    if search_key:
        try:
            uid_user = User.query.get(uid)
<<<<<<< HEAD
            operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_ROLE,operation=OperationType.QUERY,detail=f'搜索角色：{search_key}')
=======
            operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_ROLE,
                                         operation=OperationType.QUERY, detail=f'搜索角色：{search_key}')
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
            db.session.add(operation_log)
            db.session.commit()
        except Exception as e:
            print(e)
        query = query.filter(Role.name.like(f'%{search_key}%'))
<<<<<<< HEAD
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    # 获取分页对象
    pagination = query.paginate(
        page=page,
        per_page=page_size,
        error_out=False
    )
<<<<<<< HEAD
    
    # 获取当前页的用户列表
    roles = [role.to_json() for role in pagination.items]
    
    # 获取总用户数
    total = pagination.total
    
=======

    # 获取当前页的用户列表
    roles = [role.to_json() for role in pagination.items]

    # 获取总用户数
    total = pagination.total

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    data = {
        'total': total,
        'roles': roles
    }
<<<<<<< HEAD
    
    return jsonify({'message':'获取角色列表成功','errcode':'0','data':data}),200


@admin_bp.route('/admin/role/add',methods=['POST'])
=======

    return jsonify({'message': '获取角色列表成功', 'errcode': '0', 'data': data}), 200


@admin_bp.route('/admin/role/add', methods=['POST'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_ROLE, OperationType.ADD)
def role_add():
    name = request.json.get('name')
    code = request.json.get('code')
    description = request.json.get('description')
    uid = request.json.get('uid')

<<<<<<< HEAD
    role = Role(name=name,code=code,description=description)
    uid_user = User.query.get(uid)
    operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_ROLE,operation=OperationType.ADD,detail=f'添加角色：{name}')
=======
    role = Role(name=name, code=code, description=description)
    uid_user = User.query.get(uid)
    operation_log = OperationLog(user_id=uid, email=uid_user.email,
                                 module=ModuleType.ADMIN_ROLE, operation=OperationType.ADD, detail=f'添加角色：{name}')
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    db.session.add(role)
    db.session.add(operation_log)
    try:
        db.session.commit()
<<<<<<< HEAD
        return jsonify({'message':'添加角色成功','errcode':'0'}),200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':'添加加角色失败','errcode':'-1','error':str(e)}),500
    
    
@admin_bp.route('/admin/role/edit',methods=['PUT'])
=======
        return jsonify({'message': '添加角色成功', 'errcode': '0'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '添加加角色失败', 'errcode': '-1', 'error': str(e)}), 500


@admin_bp.route('/admin/role/edit', methods=['PUT'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_ROLE, OperationType.UPDATE)
def role_edit():
    id = request.json.get('id')
    name = request.json.get('name')
    code = request.json.get('code')
    description = request.json.get('description')
    uid = request.json.get('uid')

    role = Role.query.get(id)
    role.name = name
    role.code = code
    role.description = description
    try:
        db.session.commit()
        uid_user = User.query.get(uid)
<<<<<<< HEAD
        operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_ROLE,operation=OperationType.UPDATE,detail=f'更新角色：{name}')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message':'更新角色成功','errcode':'0'}),200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':'更新角色失败','errcode':'-1','error':str(e)}),500


@admin_bp.route('/admin/role/delete',methods=['DELETE'])
=======
        operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_ROLE,
                                     operation=OperationType.UPDATE, detail=f'更新角色：{name}')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message': '更新角色成功', 'errcode': '0'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '更新角色失败', 'errcode': '-1', 'error': str(e)}), 500


@admin_bp.route('/admin/role/delete', methods=['DELETE'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_ROLE, OperationType.DELETE)
def role_delete():
    id = request.json.get('id')
    uid = request.json.get('uid')
    role = Role.query.get(id)
    uid_user = User.query.get(uid)
<<<<<<< HEAD
    operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_ROLE,operation=OperationType.DELETE,detail=f'删除角色：{role.name}')
=======
    operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_ROLE,
                                 operation=OperationType.DELETE, detail=f'删除角色：{role.name}')
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    try:
        db.session.delete(role)
        db.session.add(operation_log)
        db.session.commit()
<<<<<<< HEAD
        return jsonify({'message':'删除角色成功','errcode':'0'}),200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':'删除角色失败','errcode':'-1','error':str(e)}),500



@admin_bp.route('/admin/role/all',methods=['GET'])
def role_all():
    roles = Role.query.all()
    role_list = [{'name': role.name, 'code': role.code} for role in roles]
    return jsonify({'message':'获取所有角色成功','errcode':'0','data':role_list}),200
=======
        return jsonify({'message': '删除角色成功', 'errcode': '0'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '删除角色失败', 'errcode': '-1', 'error': str(e)}), 500


@admin_bp.route('/admin/role/all', methods=['GET'])
def role_all():
    roles = Role.query.all()
    role_list = [{'name': role.name, 'code': role.code} for role in roles]
    return jsonify({'message': '获取所有角色成功', 'errcode': '0', 'data': role_list}), 200
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c


def build_permission_tree(permissions):
    # 创建模块级别的树节点
    module_map = {}
<<<<<<< HEAD
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    for permission in permissions:
        # 如果模块还不存在，创建新的模块节点
        if permission.module not in module_map:
            module_map[permission.module] = {
                'id': f'module_{permission.module}',  # 创建虚拟ID避免与权限ID冲突
                'label': permission.module,  # 使用模块名称作为标签
                'children': []
            }
        # 将权限作为子节点添加到对应模块下
        module_map[permission.module]['children'].append({
            'id': permission.id,
            'label': f'{permission.operation}',  # 操作名称作为标签
            'description': permission.description
        })

    # 将字典转换为列表
    return list(module_map.values())


<<<<<<< HEAD
@admin_bp.route('/admin/role/permission',methods=['GET'])
=======
@admin_bp.route('/admin/role/permission', methods=['GET'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_ROLE, OperationType.QUERY)
def role_permission():
    role_id = request.args.get('id')
    all_permissions = Permission.query.all()
    permission_tree = build_permission_tree(all_permissions)
    role_permissions = RolePermission.query.filter_by(role_id=role_id).all()
    checked_permissions = [rp.permission_id for rp in role_permissions]
<<<<<<< HEAD
    
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    return jsonify({
        'message': '获取角色权限成功',
        'errcode': '0',
        'data': {
            'permissionTree': permission_tree,
            'checkedKeys': checked_permissions
        }
    }), 200
<<<<<<< HEAD
    


@admin_bp.route('/admin/role/permission/update',methods=['PUT'])
=======


@admin_bp.route('/admin/role/permission/update', methods=['PUT'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_ROLE, OperationType.UPDATE)
def role_permission_update():
    role_id = request.json.get('role_id')
    permission_ids = request.json.get('permissionIds', [])
    uid = request.json.get('uid')
    role = Role.query.get(role_id)
<<<<<<< HEAD
    
    try:
        role.permissions = []
        if permission_ids:
            permissions = Permission.query.filter(Permission.id.in_(permission_ids)).all()
            role.permissions.extend(permissions)
            
        uid_user = User.query.get(uid)
        operation_log = OperationLog(
                user_id=uid,
                email=uid_user.email,
                module=ModuleType.ADMIN_ROLE,
                operation=OperationType.UPDATE,
                detail=f'更新角色权限：{role.name}'
            )
    
=======

    try:
        role.permissions = []
        if permission_ids:
            permissions = Permission.query.filter(
                Permission.id.in_(permission_ids)).all()
            role.permissions.extend(permissions)

        uid_user = User.query.get(uid)
        operation_log = OperationLog(
            user_id=uid,
            email=uid_user.email,
            module=ModuleType.ADMIN_ROLE,
            operation=OperationType.UPDATE,
            detail=f'更新角色权限：{role.name}'
        )

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message': '更新角色权限成功', 'errcode': '0'}), 200
    except Exception as e:
        print(e)
        db.session.rollback()
<<<<<<< HEAD
        return jsonify({'message': '更新角色权限失败', 'errcode': '-1', 'error': str(e)}), 500
=======
        return jsonify({'message': '更新角色权限失败', 'errcode': '-1', 'error': str(e)}), 500
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
